package classify.BinaryTree;

import object.TreeNode;

/**
 * @author sps
 * @date 2023/5/20 22:20
 */
public class tree {

    int res = 0;
    public int maxSumBST(TreeNode root) {
        if(root == null)return 0;
        dfsRoot(root);
        return res;
    }

    private int[] dfsRoot(TreeNode root) {
        int cur = 0;
        int[] left = new int[]{Integer.MAX_VALUE,Integer.MIN_VALUE,0};
        int[] right = new int[]{Integer.MAX_VALUE,Integer.MIN_VALUE,0};
        if(root.left != null){
            left = dfsRoot(root.left);
        }
        if(root.right != null){
            right = dfsRoot(root.right);
        }
        if(root.val > left[1] && root.val < right[0]){
            cur = root.val + left[2] + right[2];
            left[1] = root.val;
            right[0] = root.val;
        }else {
            cur = 0;
            right = new int[]{Integer.MIN_VALUE,Integer.MAX_VALUE,0};
            left = new int[]{Integer.MIN_VALUE,Integer.MAX_VALUE,0};
        }
        res = Math.max(res,cur);
        return new int[]{Math.min(left[0],root.val),Math.max(right[1],root.val),cur};
    }
}
